import React, {Component} from 'react';
import { observable, action, computed, autorun, toJS } from 'mobx';
import {Tools, Bubble, Toast } from 'weaver-mobile';
import { ListViewPage } from 'weaver-mobile-page';
import BaseStore from '../BaseStore';
import {getLocation} from '../../util/jemUtil';
import ListItem from '../../components/outSignV2/locationList/ListItem';
import MapUtil from '../../util/mapUtil';

const getLabel = Tools.getLabel;

class LocationStore extends BaseStore{
    //#region 地图相关
    @observable mapUtil = new MapUtil();

    draw = () => {}

    @action onMapTypeChangeHandle = async () => {
        Toast.loading('loading', 0);
        this.locationInfo = await getLocation(this.mapUtil);
        this.outSignStoreV2.mapUtil.setMapType(this.mapUtil.currentMapType);
        this.getLocations(1);
        Toast.hide();
    }
    //#endregion

    //#region 地理位置
    @observable _locationInfo = {};
    @computed get locationInfo(){return toJS(this._locationInfo)}
    set locationInfo(v){this._locationInfo = v}

    @computed get hasLocationInfo(){
        const {longitude, latitude} = this.locationInfo;
        return longitude != null && longitude != '' && latitude != null && latitude != '';
    }
    //#endregion

    //#region 获取外勤应用设置
    get poitypes(){
        const {outSignSetting} = this.outSignStoreV2 || {};
        const {poitypes} = outSignSetting || {};
        return poitypes ||'';
    }
    //#endregion

    //#region 初始化数据
    @observable _outSignStoreV2;
    @computed get outSignStoreV2(){return this._outSignStoreV2}
    set outSignStoreV2(v){this._outSignStoreV2 = v}

    // monitorMapType = () => {
    //     const {currentMapType} = this.outSignStoreV2 || {};
    //     this.mapStore.setMapType(currentMapType);
	// }
    // monitor = autorun(this.monitorMapType);

    @action clearMapData = () => {
        const {currentMapType} = this.outSignStoreV2.mapUtil;
        this.mapUtil.setMapType(currentMapType);
    }

    @action cleanLocationData = () => {
        this.listViewStore = new ListViewPage.Store();
        this.locationList = [];
        this.currentPage = 1;
        this.selectedLocationId = 0;
    }

    @action init = () => {
        const {locationInfo} = this.outSignStoreV2;
        this.locationInfo = locationInfo;
        this.clearMapData();
        this.getLocations(1);
    }
    //#endregion

    //#region 获取附近位置
    @observable listViewStore = new ListViewPage.Store();
    @observable currentPage = 1;
    @observable selectedLocationId = 0;
    @observable _locationList = [];
    @computed get locationList(){return toJS(this._locationList)}
    set locationList(v){this._locationList = v}

    @computed get listViewPageProps(){
        return {
            style: {
                height: '100%'
            },
            store: this.listViewStore,
            onRefresh: () => this.getLocations(1),
            onEndReached: () => this.getLocations(),
            renderFooter: () => {
                if (this.listViewStore.loading) {
                    return (
                    <div style={{ padding: 30, textAlign: 'center' }}>
                        Loading...
                    </div>
                    );
                } else if (!this.listViewStore.hasMore) {
                    return (
                    <div className='nomore'>
                        <span className='left' />
                        <span className='name'>{getLabel(390064, '没有更多啦')}</span>
                        <span className='right' />
                    </div>
                    );
                }
                return null;
            },
            getTemplate: template => {
                return {
                    ...template,
                    default: [{
                        key: 'col1',
                        render: data => (
                            <ListItem data={data} store={this} />
                        )
                    }]
                }
            }
        }
    }

    @action getLocations = async pageIndex => {
        if(pageIndex == null)
            this.currentPage++;
        else if(pageIndex == 1){
            this.cleanLocationData();
        }

        this.listViewStore.setState({
            loading: false
        });

        let datas = [];
        if(this.mapUtil.isAmap){
            const {longitude, latitude} = this.locationInfo;
            const radius = window.queryRadius || 1000;
            datas = await this.mapUtil.queryLocations({longitude, latitude, radius, types: this.poitypes, page: this.currentPage});
        }else if(this.mapUtil.isGoogleMap){
            datas = this.locationInfo.locationList || [];
            datas = datas.map((d, idx) => {
                return {
                    ...d, 
                    id: ((pageIndex || 1) - 1) * 50 + idx,
                }
            })
        }
        this.locationList = [...this.locationList, ...datas];
        const dataSource = this.listViewStore.dataSource.cloneWithRows(this.locationList);
        this.listViewStore.setState({
            nameKey: 'name',
            rowKey: 'id',
            data: this.locationList,
            pageSize: window.queryLocationPageSize || 50,
            dataSource,
            hasMore: datas.length > 0,
            loading: false,
            isTable: false,
            getData: () => {}
        });
        this.currentPage == 1 && this.locationList.length > 0 && this.onLocationChangeHandle(0);
    }

    @action onLocationChangeHandle = async id => {
        this.selectedLocationId = id;
        const p = this.locationList[id];
        const {name, address, longitude, latitude} = p;
        this.locationInfo = {...this.locationInfo, name, address, longitude, latitude};
        this.draw();
    }

    @action onBtnClickHandle = callback => {
        this.outSignStoreV2.onLocationChangeHandle(this.locationInfo);
        callback && callback();
    }
    //#endregion
}

export const locationStore = new LocationStore(); 